package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.PostDao;
import com.example.simpleforum.dao.ReplyDao;
import com.example.simpleforum.model.Post;
import com.example.simpleforum.model.Reply;
import com.example.simpleforum.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 个人中心Servlet
 */
public class UserCenterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 查询用户发布的帖子
        PostDao postDao = new PostDao();
        List<Post> posts = postDao.findPostsByUserId(user.getId());
        
        // 查询用户发布的回复
        ReplyDao replyDao = new ReplyDao();
        List<Reply> replies = replyDao.findRepliesByUserId(user.getId());
        
        // 将数据存入请求属性
        request.setAttribute("posts", posts);
        request.setAttribute("replies", replies);
        
        // 转发到个人中心页面
        request.getRequestDispatcher("/userCenter.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // POST请求也执行相同操作
        doGet(request, response);
    }
}